package com.jwt.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.jwt.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtInterceptHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String fullToken = request.getHeader("token");
        if (StringUtils.isEmpty(fullToken)) {
            throw new RuntimeException("获取token失败");
        }
        String[] tokenSplit = fullToken.split("Authorization: Bearer ");
        if (tokenSplit.length != 2) {
            throw new RuntimeException("token格式不正确");
        }
        String token = tokenSplit[1];
        if (!StringUtils.isEmpty(token)) {
            try {
                JwtUtil.verifyToken(token);
                return true;
            } catch (SignatureVerificationException e) {
                log.info("无效签名！ 错误 ->", e);
            }
            catch (Exception e) {
                log.info("错误信息：{}", e.getMessage());
            }
        }
        return false;
    }
}
